from version import Version
import os


class AppException(Exception):
	'''General Application exception'''


class AppNotFound(AppException):
	'''Application with given name not found'''


class NoVersions(AppException):
	'''No versions available for application'''


class InvalidDir(AppException):
	'''Invalid application name'''

	invalid_paths = ['.svn','tweaks']


class Application(object):
	'''Application info

	@property versions application versions
	@property last_version last application version
	'''

	def __init__(self, name, top):
		"""Init application

		@param name application name
		@param top application database
		"""

		if name in InvalidDir.invalid_paths:
			raise InvalidDir
		self.app_path = os.path.join(top, name)
		if not os.path.exists(self.app_path):
			raise AppNotFound
		self.name = name
		self._refresh()

	def _refresh(self):
		'''Update version list'''

		self.versions = [ ]
		if len(os.listdir(self.app_path)) < 1:
			raise NoVersions
		for path in os.listdir(self.app_path):
			if os.path.isdir(os.path.join(self.app_path,path)) and not (path == '.svn'): #excluding .svn for convenience reasons
				self.versions.append(Version(self.name, path, os.path.join(self.app_path, path)))
		self.versions = sorted(self.versions)
	
	def versions(self):
		'''Get versions.'''
	
		self._refresh()
		return self.versions
		
		
	def last_version(self):
		'''Get latest application version'''
		
		self._refresh()
		return max(self.versions)
